﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using FairyWorld.Models;
using System.IO;
using System.Net.Mail;


namespace FairyWorld.Controllers
{
    public class UserController : Controller
    {
        /// <summary>
        /// 文件路径，用户空间，数据库句柄
        /// </summary>
        const string FilePath = @"C:\Users\huangjingwei\Documents\Visual Studio 2012\Projects\test1\FairyWorld\";
        const int space = 1024 * 1024 * 100;
        SrcManager srcDB = new SrcManager();
        //
        // GET: /User/
        /// <summary>
        /// 用户主页
        /// </summary>
        /// <returns>用户主页</returns>
        public ActionResult Index()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user = GetUser("roles.group.creator");
            ViewBag.User = user;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(user);
        }

        /// <summary>
        /// 用户信息编辑
        /// </summary>
        /// <returns>用户信息编辑视图</returns>
        public ActionResult Edit()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user = GetUser("");
            ViewBag.User = user;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(user);
        }

        /// <summary>
        /// 用户信息修改
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns>信息视图</returns>
        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User current = GetUser("");
            current.username = user.username;
            current.password = user.password;
            current.ConfirmPassword = user.ConfirmPassword;
            current.phone = user.phone;
            RecordLog(new Logs
            {
                time = DateTime.Now,
                action = "EditUser",
                description = "Edit",
            });
    //        User user1 = srcDB.users.ToList().Find(u => u.email == user.email);
    //        User user2 = srcDB.users.ToList().Find(u => u.password == user.password);

   //         if (user1 == null && user2 == null || current.email == user.email)
   //         {
  //              current.email = user.email;
                srcDB.SaveChanges();
                return RedirectToAction("Info", "User");
    //        }
     //       else
     //           ModelState.AddModelError("", "信息不合法！");

     //       return View();
        }

        /// <summary>
        /// 用户信息现实
        /// </summary>
        /// <returns>信息视图</returns>
        public ActionResult Info()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user = GetUser("fold");
            int size = GetSize(user.fold);
            ViewBag.User = user;
            ViewBag.Size = size;
            ViewBag.Space = space - size;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(user);
        }

        /// <summary>
        /// 删除文件或文件夹
        /// </summary>
        /// <param name="name">文件名</param>
        /// <param name="tag">文件类型</param>
        [HttpPost]
        public void Delete(string name, int tag)
        {
   //         if (!Validation())
   //             return RedirectToAction("Index", "Home");
            Fold mfolder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = mfolder.files.Find(a => a.filename == name);
            Fold zfolder = mfolder.folds.Find(a => a.foldname == name);
            if (file != null)
            {
                DeleteFile(file);
                RecordLog(new Logs
                {
                    time = DateTime.Now,
                    action = "DeleteFile",
                    description = this.HttpContext.Session["path"] + file.filename,
                });
            }
            if (zfolder != null)
            {
                DeleteFold(zfolder);
                RecordLog(new Logs
                {
                    time = DateTime.Now,
                    action = "DeleteFolder",
                    description = this.HttpContext.Session["path"] + zfolder.foldname + @"/",
                });
            }
            srcDB.SaveChanges();
   /*         string str = "Music";
            if (tag == 2)
                str = "Image";
            else if (tag == 3)
                str = "Doc";
            else if (tag == 4)
                str = "Files";
            return RedirectToAction(str);*/
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="name">下载文件名</param>
        /// <param name="tag">文件类型</param>
        public void Download(string name, int tag)
        {
  //          if (!Validation())
  //              return RedirectToAction("Index", "Home");
            Fold mfolder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = mfolder.files.Find(a => a.filename == name);
            file = srcDB.files.Include("logs").Single(f => file.MyFileId == f.MyFileId);
            Logs log = new Logs
            {
                action = "Download",
                description = this.HttpContext.Session["path"] + file.filename,
                time = DateTime.Now
            };
            RecordLog(log);
            file.logs.Add(log);
            DownloadFile(file);
            srcDB.SaveChanges();
  /*          string str = "Music";
            if (tag == 2)
                str = "Image";
            else if (tag == 3)
                str = "Doc";
            else if (tag == 4)
                str = "Files";
            return RedirectToAction(str);*/
        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="fold">文件夹名</param>
        /// <param name="tag">文件类型</param>
        /// <returns>0</returns>
        [HttpPost]
        public int AddFolder(string fold, int tag)
        {
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            List<Fold> foldList = srcDB.folds.Single(a => a.FoldId == folder.FoldId).folds;
            for (int i = 0; i < foldList.Count; i++)
            {
                if (foldList[i].foldname == fold)
                    return 0;
            }
            foldList.Add(new Fold(){foldname = fold});
            RecordLog(new Logs
            {
                action = "AddFolder",
                description = this.HttpContext.Session["path"] + fold,
                time = DateTime.Now
            });
            srcDB.SaveChanges();
            return 1;
  /*          string str = "Music";
            if (tag == 2)
                str = "Image";
            else if (tag == 3)
                str = "Doc";
            else if (tag == 4)
                str = "Files";
            return RedirectToAction(str);*/
        }

        public ActionResult Music()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        public ActionResult LogManager()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user= GetUser("logs");
            user.logs.ForEach(a => a.description = translate(a));
            ViewBag.User = user;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(user.logs.OrderByDescending(u => u.time).ToList());
        }

        public ActionResult FileDetail(string name, int tag)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = folder.files.Single(u => u.filename == name);
            file = srcDB.files.Include("logs").Single(u => u.MyFileId == file.MyFileId);
            file.logs.ForEach(u => u.description = translate(u));
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(file.logs.OrderByDescending(u => u.time).ToList());
        }

        [HttpPost]
        public ActionResult Music(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        public ActionResult Image()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        [HttpPost]
        public ActionResult Image(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        public ActionResult Doc()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        [HttpPost]
        public ActionResult Doc(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        public ActionResult Files()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        [HttpPost]
        public ActionResult Files(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        public ActionResult Contact()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user = GetUser("roles.group");
            List<Group> groups = new List<Group>();
            user.roles.ForEach(a => groups.Add(a.group));
            HashSet<User> users = new HashSet<User>();
            groups.ForEach(g => GetGroup("roles.user", g.GroupId).roles
                  .ForEach(u => users.Add(u.user)));
            ViewBag.User = user;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(users.ToList());
        }

        [HttpPost]
        public ActionResult Contact(string data, string letter)
        {
            String[] ids = data.Split('_');
            User cur_user = GetUser("logs");
            foreach (var st in ids)
                if (st != null && st.Length > 0)
                {
                    int id = int.Parse(st);
                    User user1 = srcDB.users.Include("letters").Single(u => u.UserId == id);
                    user1.letters.Add(new Letter()
                    {
                        check = false,
                        action = letter,
                        time = DateTime.Now,
                        username = cur_user.username,
                        senderId = cur_user.UserId
                    });
                    cur_user.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "SendLetter",
                        description = user1.username + ">:" + letter,
                        time = DateTime.Now
                    });
                    user1.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "NewLetter",
                        description = cur_user.username + ">:" + letter,
                        time = DateTime.Now
                    });
                }
            srcDB.SaveChanges();
            return RedirectToAction("Contact");
        }

        public int GetUncheckedLetters()
        {
            User user = GetUser("letters");
            int count = 0;
            for (int i = 0; i < user.letters.Count; i++)
            {
                if (user.letters[i].check == false)
                    count++;
            }
            return count;
        }

        public ActionResult Letters()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            User user = GetUser("letters");
            ViewBag.User = user;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(user);
        }

        [HttpPost]
        public ActionResult Letters(int id)
        {
            Letter letter = srcDB.letters.Single(d => d.LetterId == id);
            letter.check = true;
            RecordLog(new Logs
            {
                action = "CheckLetter",
                description = letter.username+"<:"+letter.action,
                time = DateTime.Now
            });
            srcDB.SaveChanges();
            return RedirectToAction("Letters");
        }

        public ActionResult AddGroup(string name)
        {
            RecordLog(new Logs
            {
                action = "CreateGroup",
                description = name,
                time = DateTime.Now
            });
            User current = GetUser("roles");
            Role role = new Role() { user = current, power = 2 };
            Group newgroup = new Group()
            {
                groupname = name,
                createTime = DateTime.Now.ToString(),
                creator = current,
                fold = new Fold(),
                roles = new List<Role> { role }
            };
            role.group = newgroup;
            current.roles.Add(role);
            srcDB.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult DeleteGroup(int id)
        {
            Group group = srcDB.groups.Include("roles").Single(u => u.GroupId == id);
            RecordLog(new Logs
            {
                action = "DeleteGroup",
                description = group.groupname,
                time = DateTime.Now
            });
            List<int> roles = group.roles.Select(r => r.RoleId).ToList();
            roles.ForEach(a => srcDB.roles.Remove(srcDB.roles.Single(u => u.RoleId == a)));
            srcDB.groups.Remove(group);
            srcDB.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult LeaveGroup(int id)
        {
            User user = GetUser("roles.group");
            Role role = user.roles.Single(r => r.group.GroupId == id);
            RecordLog(new Logs
            {
                action = "LeaveGroup",
                description = role.group.groupname,
                time = DateTime.Now
            });
            srcDB.roles.Remove(srcDB.roles.Single(r => r.RoleId == role.RoleId));
            srcDB.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult SendEmail(string emailaddresses)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Email email = new Email();
            email.emailaddresses = emailaddresses;
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(email);
        }
        [HttpPost]
        public ActionResult SendEmails(Email sendemail)
        {
            String[] emails = sendemail.emailaddresses.Split(';');
            User cur_user = GetUser("logs");
            foreach (string email in emails)
            {
                if (email != "")
                {
                    SendMail(sendemail.subject, sendemail.message, email);
                    cur_user.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "SendEmail",
                        description = email + ">:" + sendemail.subject + "%" + sendemail.message,
                        time = DateTime.Now
                    });
                    User user1 = srcDB.users.Include("logs").Single(s => s.email == email);
                    user1.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "NewEmail",
                        description = cur_user.email + ">:" + sendemail.subject + "%" + sendemail.message,
                        time = DateTime.Now
                    });
                }
            }
            srcDB.SaveChanges();
            return RedirectToAction("Contact");
        }
        
        private User GetUser(string url)
        {
            if (url.Length > 0)
            {
                return srcDB.users
                        .Include(url)
                        .ToList()
                        .Single(u => u.UserId == int.Parse(
                            this.HttpContext.Session["user"].ToString()));
            }
            else
            {
                return srcDB.users
                        .ToList()
                        .Single(u => u.UserId == int.Parse(
                            this.HttpContext.Session["user"].ToString()));
            }
        }

        private Group GetGroup(string url, int id)
        {
            if (url.Length > 0)
            {
                return srcDB.groups
                        .Include(url)
                        .ToList()
                        .Single(u => u.GroupId == id);
            }
            else
            {
                return srcDB.groups
                        .ToList()
                        .Single(u => u.GroupId == id);
            }
        }

        private Fold GetFolder(string url)
        {
            string[] paths = url.Split('/');
            User user = GetUser("fold");
            Fold result = user.fold;
            foreach (var path in paths)
            {
                if (path.Length > 0)
                    result = srcDB.folds
                              .Include("folds")
                              .ToList()
                              .Single(u => u.FoldId == result.FoldId)
                              .folds
                              .ToList()
                              .Single(u => u.foldname == path);
            }
            
            result = srcDB.folds.Include("folds")
                .Single(u => u.FoldId == result.FoldId);
            return result;
        }

        private bool Validation()
        {
            return this.HttpContext.Session["user"] != null;
        }

        private Fold InitFolder()
        {
            Fold folder = GetFolder("/");
            this.HttpContext.Session["path"] = "/";
            folder.files = folder.files.Select(a => srcDB.files.Include("creator").Single(u => a.MyFileId == u.MyFileId)).ToList();
            return folder;
        }

        private Fold UpdateFolder(string op)
        {
            if (op[0] == '+')
            {
                this.HttpContext.Session["path"] =
                    this.HttpContext.Session["path"].ToString() + op.Substring(1) + "/";
            }
            else if(op[0] == '-')
            {
                string str = this.HttpContext.Session["path"].ToString();
                int t = str.Length - 1;
                while (t > 0 && str[t - 1] != '/')
                    --t;
                this.HttpContext.Session["path"] = str.Substring(0, t);
            }
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            folder.files = folder.files.Select(a => srcDB.files.Include("creator").Single(u => a.MyFileId == u.MyFileId)).ToList();
            return folder;
        }

        private void DeleteFile(MyFile file)
        {
            System.IO.File.Delete(Server.MapPath(file.url).Substring(0, Server.MapPath("").Length - 4)+file.url);
            if (file.tag == 2)
            {
                System.IO.File.Delete(Request.MapPath("~/Content/files/thumbnail/") + file.MyFileId+"_"+file.filename);
            }
            srcDB.files.Remove(file);
        }

        private void DownloadFile(MyFile file)
        {
            //ASP.NET下载文件(弹出打开保存文件对话框) 
            try
            {
                //FileName--要下载的文件名
                string FileName = Server.MapPath(file.url).Substring(0, Server.MapPath("").Length - 4) + file.url;

                FileInfo DownloadFile = new FileInfo(FileName);
                if (DownloadFile.Exists)
                {
                    file.hot += 1;
                    srcDB.SaveChanges();
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Buffer = false;
                    Response.ContentType = "application/octet-stream";
                    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
                    Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                    Response.WriteFile(DownloadFile.FullName);
                    Response.Flush();
                    Response.End();

                    string[] strArray = FileName.Split('_');
                    System.IO.File.Move(FileName, strArray[strArray.Length - 1]);    
                }
                else
                {
                    //文件不存在
                }
            }
            catch
            {
                //打开时异常了
            }

        }

        private void DeleteFold(Fold folder)
        {
            folder = srcDB.folds.Include("folds").Include("files").Single(a => a.FoldId == folder.FoldId);
            List<Fold> folders = folder.folds.ToList();
            folders.ForEach(a => DeleteFold(a));
            List<MyFile> files = folder.files.ToList(); 
            files.ForEach(a => DeleteFile(a));
            srcDB.folds.Remove(folder);
        }

        private int GetSize(Fold folder)
        {
            int size = 0;
            folder = srcDB.folds.Include("folds").Include("files").Single(u => u.FoldId == folder.FoldId);
            folder.files.ForEach(u => size += u.size);
            folder.folds.ForEach(u => size += GetSize(u));
            return size;
        }

        [HttpPost]
        public ActionResult UpdateIcon(string url)
        {
            User user = GetUser("");
            user.iconUrl = url;
            srcDB.SaveChanges();
            return RedirectToAction("Edit");
        }

        public void SearchFiles(Fold folder, List<MyFile> filesSearch)
        {
            foreach(Fold subfolder in folder.folds)
                SearchFiles(subfolder, filesSearch);
            foreach (MyFile file in folder.files)
            {
                int flag = file.filename.IndexOf(HttpContext.Session["searchkey"].ToString());
                if (flag != -1)
                    filesSearch.Add(file);
            }
        }
        public ActionResult Search(string key)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            HttpContext.Session["searchkey"] = key;
            Fold folder = InitFolder();
            ViewBag.User = GetUser("");
            List<MyFile> filesSearch = new List<MyFile>();
            SearchFiles(folder, filesSearch);
            ViewBag.letterCount = GetUncheckedLetters();
            return View(filesSearch);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ContentResult Import(HttpPostedFileBase FileData, string folder, string name)
        {
            string result = "";
            if (null != FileData)
            {
                try
                {
                    result = Path.GetFileName(FileData.FileName);//获得文件名
                    string ext = Path.GetExtension(FileData.FileName).ToLower();//获得文件扩展名
                    //           string saveName = "uploadfile" + ext;//实际保存文件名
                    string saveName = result;// +ext;

                    Fold currentFolder = GetFolder(this.HttpContext.Session["path"].ToString());
                    if (currentFolder.files.Find(u => u.filename == saveName) != null)
                        return Content("x");
 
                    MyFile newFile = new MyFile() { createTime = DateTime.Now.ToString() };
                    newFile.filename = saveName;
                    newFile.createTime = DateTime.Now.ToLocalTime().ToString();
      //              newFile.creator = GetUser("");
                    newFile.size = FileData.ContentLength;
                    if (ext == ".mp3" || ext == ".avi" || ext == "wav" || ext == ".wma") 
                        newFile.tag = 1;
                    else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                        newFile.tag = 2;
                    else if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx" || ext == ".pdf" || ext==".txt" || ext==".ppt" || ext==".pptx")
                        newFile.tag = 3;
                    else
                        newFile.tag = 4;
                    RecordLog(new Logs
                    {
                        action = "ImportFile",
                        time = DateTime.Now,
                        description = this.HttpContext.Session["path"] + newFile.filename
                    });
                    currentFolder.files.Add(newFile);
                    srcDB.SaveChanges();
                    int fileId = currentFolder.files.Single(u => u.filename == saveName).MyFileId;
                    saveName = fileId + "_" + saveName;
                    currentFolder.files.Single(u => u.MyFileId == fileId).url= "Content/files/" + saveName;
                    srcDB.SaveChanges();
                    saveFile(FileData, folder, saveName);//保存文件
                    if (newFile.tag == 2)
                    {
                        string phyPath = Request.MapPath("~" + folder + "/");
                        //生成缩略图
                        System.Drawing.Image srcImage = System.Drawing.Image.FromFile(phyPath + saveName);
                        int width = 90 * srcImage.Width / srcImage.Height;
                        System.Drawing.Image newImage = srcImage.GetThumbnailImage(width, 90, null, IntPtr.Zero);
                
                        newImage.Save(phyPath + "thumbnail/" + saveName);
                    }
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ImportIcon(HttpPostedFileBase FileData, string folder, string name)
        {
            string result = "";

            if (null != FileData)
            {
                try
                {
                    result = Path.GetFileName(FileData.FileName);
                    User user = GetUser("");
                    string ext = Path.GetExtension(FileData.FileName).ToLower();//获得文件扩展名
                    //           string saveName = "uploadfile" + ext;//实际保存文件名
                    string saveName = user.UserId.ToString() + ext;
                    user.iconUrl = "../../content/image/head/" + saveName;
                    srcDB.SaveChanges();
                    if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp")
                    {
                        saveFile(FileData, folder, saveName);//保存文件
                    }
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            string phyPath = Request.MapPath("~" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);

            }
        }

        private void RecordLog(Logs log)
        {
            User user = GetUser("logs");
            log.user = user.username;
            user.logs.Add(log);
        }

        public void SendMail(string subject, string message,string address)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.Subject = subject;
                mail.Body = message;
                mail.From = new MailAddress("fairylandnote@gmail.com", "fairyworld资料管理平台");
                mail.To.Add(address);
                // send the e-mail
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com"; // SMTP Server Address
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential("fairylandnote@gmail.com", "fairyland123");
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }

        [HttpPost]
        public int Nothing() 
        {
            return 0;
        }

        public ActionResult LetterResponse(string senderId, string responseText) 
        {
            if (responseText != null && responseText.Length > 0)
            {
                int id = int.Parse(senderId);
                User user = srcDB.users.Include("letters").Single(u => u.UserId == id);
                user.letters.Add(new Letter()
                {
                    check = false,
                    action = responseText,
                    time = DateTime.Now,
                    username = GetUser("").username,
                    senderId = GetUser("").UserId
                });
            }
            srcDB.SaveChanges();
            return RedirectToAction("Letters");
        }

        private string translate(Logs log)
        {
            int i;
            string st1 = "", st2 = "";
            switch (log.action)
            {
                case "EditUser":
                    return "编辑个人信息";
                case "DeleteFile":
                    return "删除文件" + log.description;
                case "DeleteFolder":
                    return "删除文件夹" + log.description;
                case "Download":
                    return "下载文件" + log.description;
                case "AddFolder":
                    return "创建文件夹" + log.description;
                case "SendLetter":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "向" + st1 + "发送私信:" + st2;
                case "NewLetter":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "收到" + st1 + "发送的私信:" + st2;
                case "CheckLetter":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "阅读" + st1 + "发送的私信:" + st2;                    
                case "CreateGroup":
                    return "创建组" + log.description;
                case "DeleteGroup":
                    return "删除组" + log.description;
                case "LeaveGroup":
                    return "退出组" + log.description;
                case "SendEmail":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    return "发送email至" + st1;
                case "NewEmail":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    return "接受来自" + st1 + "的email";
                case "AddUser":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "添加用户" + st1 + "至组" + st2;
                case "NewAddUser":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被用户" + st1 + "邀请至组" + st2;
                case "Upgrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "提升" + st1 + "为组" + st2 + "的管理员";
                case "NewUpgrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st1 + "提升为组" + st2 + "的管理员";
                case "Degrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "剥夺" + st1 + "在组" + st2 + "的管理员权限";
                case "NewDegrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st1 + "剥夺在组" + st2 + "的管理员权限";
                case "DeleteGroupFile":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "删除组" + st2 + "的文件" + st1;
                case "DeleteGroupFolder":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "删除组" + st2 + "的文件夹" + st1;
                case "GroupDownload":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "下载组" + st2 + "的文件" + st1;
                case "DeleteUser":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "驱逐组" + st2 + "的用户" + st1;
                case "NewDeleteUser":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st2 + "从组" + st1 + "驱逐";
                case "AddGroupFolder":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "在组" + st2 + "中创建文件夹" + st1;
                case "EditGroup":
                    return "更改组" + log.description + "的信息";
                case "ImportFile":
                    return "上传文件到" + log.description;
                case "ImportGroupFile":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "上传文件" + st1 + "到组" + st2;
            }
            return "";
        }
    }
}
